import type { LexicalNode, NodeKey, SerializedLexicalNode } from 'lexical'
import { DecoratorNode } from 'lexical'
import type { WorkflowVariableBlockType } from '../../types'
import WorkflowVariableBlockComponent from './component.vue'
import { h, VNode } from 'vue'

export type SerializedNode = SerializedLexicalNode & {
  varName: string
  group: string
}

export class WorkflowVariableBlockNode extends DecoratorNode<VNode> {
  __varName: string
  __group:string

  static override getType(): string {
    return 'workflow-variable-block'
  }

  static override clone(node: WorkflowVariableBlockNode): WorkflowVariableBlockNode {
    return new WorkflowVariableBlockNode(node.__varName, node.__group, node.__key)
  }

  override isInline(): boolean {
    return true
  }

  constructor(varName: string, group: string,key?:NodeKey) {
    super(key)

    this.__varName = varName
    this.__group = group
  }

  override createDOM(): HTMLElement {
    const div = document.createElement('div')
    div.classList.add('inline-flex', 'items-center', 'align-middle')
    return div
  }

  override updateDOM(): false {
    return false
  }

  override decorate(): VNode {
    return h(WorkflowVariableBlockComponent,{
      key:this.__key,
      group:this.__group,
      varName:this.__varName
    })
  }

  static override importJSON(serializedNode: SerializedNode): WorkflowVariableBlockNode {
    const node = $createWorkflowVariableBlockNode(serializedNode.varName, serializedNode.group)

    return node
  }

 override exportJSON(): SerializedNode {
    return {
      type: 'workflow-variable-block',
      version: 1,
      varName: this.getVarName(),
      group: this.getGroup(),
    }
  }

  getVarName(): string {
    const self = this.getLatest()
    return self.__varName
  }

  getGroup(): string {
    const self = this.getLatest()
    return self.__group
  }

  override getTextContent(): string {
    return `{{#${this.getVarName()}#}}`
  }
}
export function $createWorkflowVariableBlockNode(key: string, group: string): WorkflowVariableBlockNode {
  return new WorkflowVariableBlockNode(key, group)
}

export function $isWorkflowVariableBlockNode(
  node: WorkflowVariableBlockNode | LexicalNode | null | undefined,
): node is WorkflowVariableBlockNode {
  return node instanceof WorkflowVariableBlockNode
}
